package org.jpropeller.problem.impl;


import org.jpropeller.collection.CList;
import org.jpropeller.problem.Problem;
import org.jpropeller.properties.Prop;
import org.jpropeller.reference.Reference;
import org.jpropeller.view.table.TableRowView;
import org.jpropeller.view.table.TableRowViewListener;
import org.jpropeller.view.table.impl.ListTableView;

/**
 * A TableRowView for Problems, where IgnorableProblems are editable.
 */
public class ProblemTableRowView implements TableRowView<Problem>
{
	String columnName;

	public ProblemTableRowView(String columnName) {
		super();
		this.columnName = columnName;
	}

	@Override
	public Object getColumn(Problem row, int column) {
		return row;
	}

	@Override
	public Class<?> getColumnClass(int column) {
		return Problem.class;
	}

	@Override
	public int getColumnCount() {
		return 1;
	}

	@Override
	public String getColumnName(int column) {
		return columnName;
	}

	@Override
	public boolean isEditable(Problem row, int column) {
		return (row instanceof IgnorableProblem) || (row instanceof NumberProblem);
	}

	@Override
	public void setColumn(Problem row, int column, Object value) {
		if(value instanceof Boolean && row instanceof IgnorableProblem)
		{
			if(!value.equals( ((IgnorableProblem)row).ignore().get() ) )
			{
				((IgnorableProblem)row).ignore().set((Boolean)value);
			}
		}
		if(value instanceof Number && row instanceof NumberProblem)
		{
			if(!value.equals( ((NumberProblem)row).number().get() ) )
			{
				((Prop)((NumberProblem)row).number()).set(value);
			}
		}
	}
	
	@Override
	public void addListener(TableRowViewListener listener) {
		//View is immutable, no changes
	}

	@Override
	public void removeListener(TableRowViewListener listener) {
		//View is immutable, no changes
	}
	
	@Override
	public void dispose() {
	}
	
	
	/**
	 * Convenience method to build a problem JTable view.
	 * @return
	 */
	public static ListTableView<Problem> makeProblemTable(Reference<? extends CList<Problem>> model,int rowHeight)
	{
		ProblemTableRowView problemRowView = new ProblemTableRowView("Problem");
		ListTableView<Problem> problemsView = new ListTableView<Problem>(model, problemRowView);
		problemsView.setDefaultRenderer(Problem.class, new ProblemCellRenderer());
		problemsView.setDefaultEditor(Problem.class, new ProblemCellEditor());
		problemsView.removeHeader();
		problemsView.setRowHeight(rowHeight);
		return problemsView;
	}
	
}
